package lock;

import threadLocalTest.Profiler;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: javase
 * @description: 公平锁与非公平锁
 * @author: lld
 * @create: 2021-04-08 22:27
 **/
public class LockFairTest {
    //创建公平锁
    private static ReentrantLock lock = new ReentrantLock(false);

    int i = 0;

    public void run() throws InterruptedException {
        if (true) {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "获得锁" + (++i));
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "获取锁失败");
        }
    }

    public static void main(String[] args) throws InterruptedException {
//        交替执行
        LockFairTest lft = new LockFairTest();
        Runnable runnable = () -> {
            try {
                for (int i = 0; i < 100; i++) {
                    lft.run();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Thread[] threadArray = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threadArray[i] = new Thread(runnable);
        }
//        Profiler.start();
        for (int i = 0; i < 10; i++) {
            threadArray[i].start();
        }
//        System.out.println("耗时："+Profiler.end());
        AbstractQueuedSynchronizer
    }
}

